import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store/auth'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
    timeout: 10000
})

// 请求拦截器（添加Token）
service.interceptors.request.use(config => {
    const authStore = useAuthStore()
    if (authStore.token) {
        config.headers.Authorization = `Bearer ${authStore.token}`
    }
    return config
})

// 响应拦截器（处理401错误）
service.interceptors.response.use(
    response => {
        // 确保返回完整响应结构
        return {
            data: response.data,
            status: response.status,
            headers: response.headers
        }
    },
    error => {
        if (error.response?.status === 401) {
            const authStore = useAuthStore()
            authStore.logout()
            ElMessage.error('会话已过期，请重新登录')
        }

        const message = error.response?.data?.message || error.message
        ElMessage.error(message)
        return Promise.reject(error)
    }
)

export default service